import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../apis/analysis.dart';
import '../../../../apis/elevator.dart';
import '../../../../controller/gather_ctrl.dart';
import '../../../../controller/network/bridge.dart';
import '../../../../model/bean/facility_ability_fean.dart';
import '../../../../model/bean/latest_analysis_bean.dart';
import '../../../../model/bean/latest_raw_data_bean.dart';
import '../../../../model/bean/lift_token.dart';

class LiftDetailsCtrl extends GatherCtrl {
  // 标记组件是否处于激活状态
  final RxBool isActivateStatus = false.obs;

  // 是否加载完成
  final RxBool isInitComplete = false.obs;

  // 组件数据集合（路由参数）
  final dataSet = {}.obs;

  // 监测设备是否存在及提示文案
  final RxBool isExistFacility = false.obs;
  final RxString facilityTipTxt = ''.obs;

  // 监测设备是否支持视频、视频连接状态、提示文案
  final RxBool viodeConnectfail = false.obs;
  final RxBool isSupportVideo = false.obs;
  final RxString videoTipTxt = ''.obs;

  // 视频流凭证
  final videoToken = Rx<LiftToken>();

  // 设备是否离线（默认离线状态）
  final RxInt offline = 1.obs;

  // 监控设备信息
  final latest = Rx<Latest>();

  // 电梯运行统计
  final latestAnalysis = Rx<LatestAnalysisBean>();

  @override
  void onInit() {
    // 创建网络变化观察
    Bridget.createNetworkCtrl(this);

    // 存储路由数据
    dataSet.value = Get.arguments;

    // print(dataSet.value);

    // 标记组件为激活状态
    isActivateStatus.value = true;

    // 读取监测设备能力
    readFacilityAbility(callback: () async {
      concurrentRequests();
    });
  }

  @override
  void onClose() {
    // 移除观察
    Bridget.delNetworkCtrl(this);
  }

  @override
  void modify() {}

  /// 读取监测设备的能力
  /// * [callback] Function|回调函数|必填
  void readFacilityAbility({@required Function callback}) async {
    Map<String, dynamic> _par = {"blackBoxNo": dataSet["monitorId"]};
    try {
      FacilityAbilityBean result = await Elevator.queryFacilityAbility(_par);
      // 验证结果
      if (result != null) analyseFacilityAbility(value: result);

      // 执行回调
      callback();
    } catch (e) {
      analyseFacilityAbility(answer: true);
    }
  }

  /// 分析监测设备能力
  /// * [answer] bool|否定答案|选填
  /// * [value] FacilityAbilityBean|接口返回结果|选填
  void analyseFacilityAbility({
    bool answer = false,
    FacilityAbilityBean value,
  }) {
    void _none() {
      isExistFacility.value = false;
      facilityTipTxt.value = "找不到监测设备";
      isSupportVideo.value = false;
      videoTipTxt.value = "找不到录像设备";
    }

    void _facility(int val) {
      if (val != 1) {
        isExistFacility.value = false;
        facilityTipTxt.value = "找不到监测设备";
      } else {
        isExistFacility.value = true;
      }
    }

    void _video(int val) {
      if (val != 1) {
        isSupportVideo.value = false;
        videoTipTxt.value = "找不到录像设备";
      } else {
        isSupportVideo.value = true;
      }
    }

    // 返回结果
    if (!answer) {
      //print(value.isExist);
      _facility(value.isExist);
      _video(value.canPlay);
    } else
      _none();
  }

  /// 跳转界面
  /// * [pageUrl] String|路由路径|必填
  /// * [args] Map|路由参数|选填
  void switchInterfacePage(String pageUrl, {Map args}) async {
    isActivateStatus.value = false;
    Get.toNamed(pageUrl, arguments: args).then((value) {
      isActivateStatus.value = true;
    });
  }

  /// 合并请求
  void concurrentRequests() async {
    Future.wait([
      readLatestAnalysis(),
      readLatestRawData(),
      readLiftToken(),
    ]).then((value) {
      isInitComplete.value = true;
      print("拿到结果了------：$value");
    });
  }

  /// 读取电梯凭证（此函数中需要验证是否存在录像设备）
  Future<bool> readLiftToken() async {
    /// 确保录像设备存在
    if (isSupportVideo.value) {
      Map<String, dynamic> _par = {"elevatorId": dataSet['liftId']};
      try {
        LiftToken result = await Elevator.queryLiftToken(_par);

        // 验证结果
        // 无返回结果标记视频加载失败
        if (result != null) {
          videoToken.value = result;
        } else {
          viodeConnectfail.value = true;
        }
      } catch (e) {
        // 视频凭证获取失败直接标记视频加载失败
        viodeConnectfail.value = true;
      }
    }
    return true;
  }

  /// 读取电梯运行统计（此函数中需要验证是否存在监测设备）
  Future<bool> readLatestAnalysis() async {
    if (isExistFacility.value) {
      LatestAnalysisBean result = await Analysis.queryLatestAnalysis(
          {"monitorId": dataSet["monitorId"]});
      if (result != null) latestAnalysis.value = result;
    }
    return true;
  }

  /// 读取电梯最新原始数据（此函数中需要验证是否存在监测设备）
  Future<bool> readLatestRawData() async {
    if (isExistFacility.value) {
      LatestRawDataBean result = await Analysis.queryLatestRawData(
          {"monitorId": dataSet["monitorId"]});
      if (result != null) {
        offline.value = result.offline;

        if (result.latest != null) {
          latest.value = result.latest;
        }
      }
    }

    return true;
  }
}
